import json

from django.db import connection

from EventMessageWeb.enums.ApiRespCodeEnums import api_response_code
from commonTool.ApiResponse import api_response
from commonTool.class_convert_tool import ClassConvertTool
from commonTool.logs.logs_wrapper import LogUtil
from manager.domain.api.upgrade_api import UpgradeAPI
from page.device.entity.Device import Device

# Create your views here.
logs = LogUtil()
resultVO = api_response()
upgrade_api = UpgradeAPI()


@logs
def get_device_info(request):
    error_enum = None
    if request.method == 'POST':
        requestData = json.loads(request.body)
        sn = requestData.get('sn')
        tp = requestData.get('tp')
        if sn and tp:
            logs.info(f"device info ----> [{sn}]  [{tp}]")
            device_info = __deviceInfo(sn, tp)
            if device_info:
                device_json_str = ClassConvertTool.convertJson(device_info)
                return resultVO.new_success(data=device_json_str)
            else:
                # 设备不存在
                error_enum = api_response_code.API_DEVICE_NOT_EXIST
        else:
            # 请输入设备信息
            error_enum = api_response_code.CUSTOM_MUST_INPUT

    # 获取最近执行的SQL语句
    queries = connection.queries
    # 打印每个SQL语句
    for query in queries:
        print(query['sql'])
    return resultVO.new_fail(enum=error_enum)


@logs
def power_set(request):
    if request.method == 'POST':
        requestData = json.loads(request.data)
        sn = requestData.get('sn')
        tp = requestData.get('tp')
        device_power_set = requestData.get('power_set')
        logs.info(f"device power set ----> [{sn}]  [{tp}]  [{device_power_set}]")
        device = __deviceInfo(sn, tp)
        if device:
            device.power_set = device_power_set
            device.save()
        else:
            error_enum = api_response_code.API_DEVICE_NOT_EXIST
            return resultVO.new_fail(enum=error_enum)
    return resultVO.new_success(msg="设置成功")


def __deviceInfo(sn, tp):
    device = Device.objects.filter(sn=sn, tp_code=tp, del_flag=0)
    if device.exists():
        return device.get()
    return None


def api_upgrade(request):
    if request.method == 'POST':
        requestData = request.POST

        username = requestData.get('username')
        deviceName = requestData.get('deviceName')
        downUrl = requestData.get('downUrl')
        md5 = requestData.get('md5')
        size = requestData.get('size')
        currentVersion = requestData.get('currentVersion')
        targetVersion = requestData.get('targetVersion')
        logs.info(
            f"device upgrade ----> [pid:{username}]  [deviceName:{deviceName}]  [downUrl:{downUrl}]  [md5:{md5}]  [size:{size}]  [当前版本:{currentVersion}]  [目标版本:{targetVersion}]")
        # 调用升级接口
        json_dict = {
            "downUrl": downUrl,
            "currentVersion": currentVersion,
            "targetVersion": targetVersion,
            "installPackSize": int(size),
            "installPackMd5": md5,
            "upRecordId": "99999",
        }
        invokerJson = {
            "info": json.dumps(json_dict).replace('"', '\"')
        }
        try:
            # 调用升级接口
            upgrade_api.upgrade_overseas_360(username, deviceName, json.dumps(invokerJson))
        except Exception as e:
            logs.error(f"device upgrade error ----> [{e}]")
            return resultVO.new_fail(enum=api_response_code.API_DEVICE_UPGRADE_ERROR)

    return resultVO.new_success()
